import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router"
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { useUserStore } from '@/store'

/**
 * 不重定向白名单
 */
export const NO_REDIRECT_WHITE_LIST = ['/login']
const { start, done } = useNProgress()

const routes: RouteRecordRaw[] = [
  {
    path: '/:path(.*)*',
    redirect: '/404',
    name: '404Page',
    meta: {
      hidden: true,
      breadcrumb: false
    }
  }
]

export const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  console.log('route to', to)
  start()
  
  const userStore = useUserStore()
  if (userStore.isLogin) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      next()
    }
  } else {
    if (NO_REDIRECT_WHITE_LIST.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
    }
  }
})

router.afterEach((to) => {
  useTitle(to?.meta?.label as string)
  done()
})
